import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;


/**
 * excel工具类
 * @author rxm
 *
 */
public class ExcelTools {
	//excel版本
	private static final String EXCEL_XLS = "xls";
    private static final String EXCEL_XLSX = "xlsx";
	
	/**
	 * 向excel中写入数据
	 * @param excelFilePath	excel文件地址 （存在直接写入，否则创建文件后在写入）
	 * @param list			写入的数据	List<List<String>>: 第一个List 对应行	第二个List对应单元格
	 * @param cloumnCount
	 * @return
	 */
	public static boolean writeExcel(String excelFilePath,List<List<String>> list){
		boolean flag = false;
		OutputStream out = null;
		try {
			File excelFile = new File(excelFilePath);
			if(!excelFile.exists()){
				excelFile.createNewFile();
			}
			//获取工作薄
			Workbook workbook = getWorkbok(excelFile);
			//获取第一工作表
			Sheet sheet1 = workbook.getSheetAt(0);
			//创建文件流，输出电子表格
			out = new FileOutputStream(excelFile);
			if(list.size() > 0){
				for(int i = 0 ; i < list.size() ; i++ ){
					//创建行
					Row row = sheet1.createRow(i);
					List<String> cellList = list.get(i);
					for(int j = 0 ; j < cellList.size() ; j++){
						//创建单元格
						Cell cell = row.createCell(j);
						//给单元格赋值
						cell.setCellValue(cellList.get(j));
					}
				}
			}
			workbook.write(out);
			flag = true;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(out != null){
					out.flush();
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
			
		return flag;
	}
	
	/**
     * 判断Excel的版本,获取Workbook
     * @param in
     * @param filename
     * @return
     * @throws IOException
     */
    public static Workbook getWorkbok(File file) throws IOException{
        Workbook wb = null;
        FileInputStream in = new FileInputStream(file);
        if(file.getName().endsWith(EXCEL_XLS)){     //Excel&nbsp;2003
            wb = new HSSFWorkbook(in);
        }else if(file.getName().endsWith(EXCEL_XLSX)){    // Excel 2007/2010
            wb = new XSSFWorkbook(in);
        }
        in.close();
        return wb;
    }
    
    public static void main(String[] args) {
    	List<List<String>> list = new ArrayList<List<String>>();
    	List<String> strList = new ArrayList<String>();
    	strList.add("小明");
    	strList.add("xiaoming");
    	for(int i = 0 ; i < 5 ; i++ ){
    		list.add(strList);
    	}
    	boolean flag = writeExcel("D:/text.xls",list);
    	System.out.println(flag);
	}
}	
